package org.zhangkun.jmsg.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.zhangkun.jmsg.webserver.server.DispatchSocket;

import sun.applet.AppletClassLoader;

public class FileUtil {

	private static ArrayList<String> tmpFiles = new ArrayList<String>();

	public static File createTempFile(String prefix, String suffix)
			throws IOException {
		File file = File.createTempFile(prefix, suffix);
		tmpFiles.add(file.getAbsolutePath());
		return file;
	}

	public static void deleteAllTempFile() {
		for (int i = 0; i < tmpFiles.size(); i++) {
			delFile(tmpFiles.get(i));
		}
	}

	public static boolean createDir(String path) {
		return new File(path).mkdirs();
	}

	public static void delFile(String path) {
		// TODO Auto-generated method stub
		new File(path).delete();
	}

	public static String getFileName(String path) {
		// TODO Auto-generated method stub
		return new File(path).getName();
	}

	public static long getFileSize(String path) {
		File f = new File(path);
		return f.length();
	}

	public static long getMktime(String path) {
		// TODO Auto-generated method stub

		return new File(path).lastModified();
	}

	public static String getParentDir(String path) {
		// TODO Auto-generated method stub
		if (path.endsWith("/") || path.endsWith("\\"))
			path = path.substring(0, path.length() - 1);
		int i = path.lastIndexOf("/");
		if (i == -1)
			i = path.lastIndexOf("\\");
		if (i == -1) {
			return null;
		}
		return path.substring(0, i + 1);
	}

	public static long getSize(String path, ScannerFilesListener listener) {
		// TODO Auto-generated method stub
		return 0;
	}

	public static String getSizeStr(long size) {
		String dw = "byte";
		double ret = size;
		if (size < 1024) {
			dw = "byte";
			ret = size;
		} else if (size < 1024 * 1024) {
			dw = "Kb";
			ret = size / 1024;
		} else if (size < 1024 * 1024 * 1024) {
			ret = size / (1024D * 1024D);
			dw = "Mb";
		} else if (size < 1024L * 1024L * 1024L * 1024L) {
			ret = size / (1024D * 1024D * 1024D);
			dw = "Gb";
		} else if (size < (1024L * 1024L * 1024L * 1024L * 1024L)) {
			ret = size / (1024D * 1024D * 1024D * 1024D);
			dw = "Tb";
		}
		String sub = String.valueOf(ret);
		if (sub.length() - sub.indexOf(".") > 2) {
			sub = sub.substring(0, sub.indexOf(".") + 3);
		}
		return sub + " " + dw;
	}

	public static boolean isDir(String path) {
		return new File(path).isDirectory();
	}

	public static boolean isExists(String path) {
		return new File(path).exists();
	}

	public static boolean isFile(String path) {
		return new File(path).isFile();
	}

	public synchronized static void initLib() {
		String dir = System.getProperty("java.io.tmpdir");
		String os = System.getProperty("os.name");
		System.setProperty("swt.library.path", dir);
		String[] files = null;
		String libDir;
		AppletClassLoader classLoader = 
				(AppletClassLoader) ClassLoader.getSystemClassLoader();
		if (os.toLowerCase().indexOf("linux") != -1) {
			// files = new String[] { "libswt-xulrunner-gtk-3740.so",
			// "libswt-glx-gtk-3740.so", "libswt-gtk-3740.so",
			// "libswt-pi-gtk-3740.so", "libswt-cairo-gtk-3740.so",
			// "libswt-xpcominit-gtk-3740.so", "libswt-gnome-gtk-3740.so",
			// "libswt-atk-gtk-3740.so", "libswt-awt-gtk-3740.so",
			// "libswt-mozilla-gtk-3740.so", "libswt-webkit-gtk-3740.so",
			// "libswt-webkit12-gtk-3740.so" };
			// libDir = "/res/lib/linux/";
//			classLoader.addEtry(new File("swt-linux"));
//			classLoader.newInstance(new URL)
		} else {
			// files = new String[] { "swt-awt-win32-3735.dll",
			// "swt-gdip-win32-3735.dll", "swt-webkit-win32-3735.dll",
			// "swt-wgl-win32-3735.dll", "swt-win32-3735.dll",
			// "swt-xulrunner-win32-3735.dll" };
			// libDir = "/res/lib/win/";
//			classLoader.addEtry(new File("swt-win"));
		}
		// for (int i = 0; i < files.length; i++)
		// try {
		//
		// System.out.println("loadLib:" + files[i]);
		// copyFile(dir + "/" + files[i],
		// FileUtil.class.getResource(libDir + files[i])
		// .openStream());
		// tmpFiles.add(dir + "" + files[i]);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	private static void copyFile(String string, InputStream is) {
		// TODO Auto-generated method stub
		File f = new File(string);
		if (f.exists()) {
			f.delete();
		}
		byte[] buffer = new byte[1024];
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(f);
			int length;
			while ((length = is.read(buffer)) != -1)
				fos.write(buffer, 0, length);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	public static void copyFile(File f1, File f2) {

		FileOutputStream fos = null;
		FileInputStream fis = null;
		if (f2.exists())
			f2.delete();
		try {
			fos = new FileOutputStream(f2);
			fis = new FileInputStream(f1);
			byte[] buffer = new byte[1024];
			int length = 0;
			while ((length = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, length);
				fos.flush();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

	}

	public static ByteArrayOutputStream readRequestData(InputStream is)
			throws Exception {
		// TODO Auto-generated method stub
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int i = 0;
		do {
			int b = -1;
			try {
				b = is.read();
			} catch (Exception e) {
				System.out.println("readRequestData Error Data{"
						+ bos.toString() + "}");
				e.printStackTrace();
				return null;
			}
			bos.write(b);
			if (b == DispatchSocket.HEADER_DECOLLATOR[i])
				i++;
			else
				i = 0;
		} while (i < DispatchSocket.HEADER_DECOLLATOR.length);

		int length = readContentLength(is, new String(bos.toByteArray()));
		bos.close();
		bos = new ByteArrayOutputStream();
		if (length > 0) {
			int readLength = 0;
			int currentReadLength = 0;
			byte[] buffer = new byte[DispatchSocket.READ_BUFFER_LENGTH];
			while (true) {
				currentReadLength = is.read(buffer);
				if (currentReadLength > 0) {
					readLength += currentReadLength;
					bos.write(buffer, 0, currentReadLength);
				}
				if (readLength == length)
					break;
			}
		}
		return bos;
	}

	private static int readContentLength(InputStream is, String string) {
		// TODO Auto-generated method stub
		Pattern p = Pattern.compile("Content-Length:(.*?)\r\n");
		Matcher m = p.matcher(string);
		if (m.find())
			return Integer.parseInt(m.group(1).trim());
		return -1;
	}

	public static void downFile(String ip, String fid, File saveFilePath) {
		FileOutputStream fos = null;
		OutputStream os = null;
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		Socket socket = null;
		try {
			socket = new Socket(ip, GlobalVar.HTTP_PORT);
			os = socket.getOutputStream();
			os.write(("GET /ReadFile.jsp?fid=" + fid + " HTTP/1.1\r\n\r\nContent-Length:0\r\n\r\n")
					.getBytes());
			os.flush();
			is = socket.getInputStream();
			baos = readRequestData(is);
			fos = new FileOutputStream(saveFilePath);
			fos.write(baos.toByteArray());
			fos.flush();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (baos != null)
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (os != null)
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (baos != null)
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	public static File getJarFile() {
		// 关键是这行...
		String path = FileUtil.class.getProtectionDomain().getCodeSource()
				.getLocation().getFile();
		try {
			path = java.net.URLDecoder.decode(path, "UTF-8"); // 转换处理中文及空格
		} catch (java.io.UnsupportedEncodingException e) {
			return null;
		}
		return new File(path);
	}
}
